package com.yellow.paymentservice.config.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author: hy
 * @create: 2024-03-14
 */
@Slf4j
@Configuration
public class MqConfig {

    @Bean
    public MessageConverter messageConverter(){
        return new Jackson2JsonMessageConverter();
    }
    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter messageConverter) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        rabbitTemplate.setMessageConverter(messageConverter);
        // 设置 ConfirmCallback
        rabbitTemplate.setConfirmCallback((CorrelationData correlationData, boolean ack, String cause) -> {
            if (ack) {
                log.info("消息发送成功: correlationData={}, ack={}, cause={}", correlationData, ack, cause);
            } else {
                // 增强错误处理逻辑
                if (cause != null && cause.contains("clean channel shutdown")) {
                    log.warn("消息发送可能成功, 通道正常关闭导致的确认延迟: correlationData={}, ack={}, cause={}", correlationData, ack, cause);
                } else {
                    log.error("消息发送失败: correlationData={}, ack={}, cause={}", correlationData, ack, cause);
                }
            }
        });

        // 设置 ReturnCallback
        rabbitTemplate.setReturnsCallback(returned -> log.warn("消息发送到交换机成功, 但未找到队列: replyCode={}, replyText={}, exchange={}, routingKey={}, message={}",
                returned.getReplyCode(),
                returned.getReplyText(),
                returned.getExchange(),
                returned.getRoutingKey(),
                returned.getMessage()));

        return rabbitTemplate;
    }
}
